package com.beyondbit.hr.api.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class BeanUtils {
    public static BeanInfo beanInfo(Class<?> clazz) throws IntrospectionException {
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        return beanInfo;
    }

    public static PropertyDescriptor[] propertyDescriptors(Class<?> clazz) throws IntrospectionException {
        return beanInfo(clazz).getPropertyDescriptors();
    }

    public static PropertyDescriptor propertyDescriptor(Class<?> clazz,String propertyName) throws IntrospectionException {
        PropertyDescriptor[] propertyDescriptors = propertyDescriptors(clazz);
        PropertyDescriptor result = null;

        for (PropertyDescriptor pd : propertyDescriptors){
            if (pd.getName().equals(propertyName)){
                result = pd;
                break;
            }
        }

        return result;
    }

    public static Object propertyValue(Object obj,String propertyName) throws Exception {
        if (obj == null)
            throw  new NullPointerException("对象不能为NULL!");

        Class<?> clazz = obj.getClass();
        PropertyDescriptor propertyDescriptor = propertyDescriptor(clazz, propertyName);
        if (propertyDescriptor == null)
            throw  new NullPointerException("没有找到属性"+propertyName);
        else{
            Method method = propertyDescriptor.getReadMethod();
            return method.invoke(obj);
        }
    }
}
